var api = require('../../../../config/api.js');
var wxcache = require('../../../../utils/wxcache.js');
var user = require('../../../../services/user.js');
const {
    request,PageContent
    } = require('../../../../utils/util.js');
Page({

    /**
     * 页面的初始数据
     */
    data: {
        swiper_attrs: {
            indicatorDots: true,
            autoplay: true,
            interval: 5000,
            duration: 1000,
            indicator_color: "#848689",
            indicator_active_color: "#f23030" 
        },
      goods_detail: { 
        // id: "orange", big_img_urls: ["/static/imgs/market/orange.jpg"], describe: " 【2019褚橙   首发预售】\n云南励志褚橙云冠橙5kg礼盒装 褚时健冰糖橙新鲜橙子 褚橙礼盒装5KG特级\n 糖橙又称无酸甜橙，果形与普通甜橙相似。因含酸量极低，果汁含量达到适当程度时即可采收、上市，是极早熟的甜橙品种。在地中海沿岸和巴西等地有少量生产，供应地方市场。 ", product_name: "云南励志褚橙云冠橙5kg礼盒装", new_price: "88", old_price: "108", sold: "100"
         },
        cart_num: 0,
        cart_num_new:0,
        has_cart: false,
        total_num: 0,
        cart_arr: [],
        goods_id: "",
        cart_goods_id:"",
        default_num: 1,
        provinceList:[],
        cityList:[]
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
      //保存this对象
      const _this = this;
      var url = api.findgoodlist;
      var data = { id: options.product_id};
      var goods_detail_info = null;
      //从后端取物品信息
      wx.request({
        url: url,
        method: "POST",
        data: {bizType:2},
        success: function (res) {
          console.log(res.data.responseBody.campaignList)
          var res_data = res.data.responseBody.campaignList
          for(var i = 0; i<res_data.length; i++){
            if (res_data[i].id == options.product_id){
              goods_detail_info = res_data[i]
            }
          }
          _this.setData({
            goods_detail: goods_detail_info,
            goods_id: options.product_id,
            cityList: goods_detail_info.cityList,
            provinceList: goods_detail_info.provinceList
          })
        }
      });
      //从后台取购物车数据
      var uid = wxcache.get("userInfo").id;
      var query_url = api.findCart;
      wx.request({
        url: query_url,
        method: 'GET',
        data: { userId: uid, pageNo: 1, pageSize: 500 },    //参数为键值对字符串
        success: function (res) {
          console.log("向后端获取购物车数据：" + res.data.responseBody.goodsCartListRespList);
          var res_arr = res.data.responseBody.goodsCartListRespList;
          for (var i = 0; i < res_arr.length; i++) {
            if (res_arr[i].goodsCart.campaignId == options.product_id) {
              _this.setData({
                cart_num_new : res_arr[i].goodsCart.num,
                cart_goods_id : res_arr[i].campaignResp.id
              })
            }
          }
        }
      })

        let arr = wx.getStorageSync('cart');
        let total_cart_count = 0;
        if (arr.length > 0) {
            for (let i in arr) {
                total_cart_count += parseInt(arr[i].count);
            }
            this.setData({
                has_cart: true,
                cart_num: total_cart_count,
                cart_arr: arr
            });
        }

    },

    minusCount: function (e) {
        let goods_detail = this.data.goods_detail;
        let num = parseInt(goods_detail.count);
        if (num <= 1) {
            return false;
        }
        num = num - 1;
        goods_detail.count = num;
        this.setData({
            goods_detail: goods_detail
        });
    },
    addCount: function (e) {
        let goods_detail = this.data.goods_detail;
        let num = parseInt(goods_detail.count);
        num = num + 1;
        goods_detail.count = num;
        this.setData({
            goods_detail: goods_detail
        });
    },
    getInputVal: function (e) {
        let goods_detail = this.data.goods_detail;
        let num = parseInt(e.detail.value);
        if (num == 0) {
            goods_detail.count = 1;
        } else {
            goods_detail.count = num;
        }
        this.setData({
            goods_detail: goods_detail
        });
    },
    addToCart: function (e) {

        var uid = wxcache.get("userInfo").id;
        var add_url = api.addCart;
        var update_url = api.updateCart;
        var good_id = this.data.goods_id;
        var cartGoodsId = this.data.cart_goods_id;
        var num = this.data.cart_num_new;
        let cart_num = this.data.cart_num;
        let cart_arr = this.data.cart_arr;
        this.setData({
            cart_num: cart_num + 1
        });
        this.data.goods_detail.count = 1;
        if (this.data.has_cart) {
            for (var i in cart_arr) {
                // 判断购物车内的item的id，和事件传递过来的id，是否相等
                if (cart_arr[i].id == this.data.goods_id) {
                    // 相等的话，给count+1（即再次添加入购物车，数量+1）
                    cart_arr[i].count = cart_arr[i].count + 1;
                    // 最后，把购物车数据，存放入缓存（此处不用再给购物车数组push元素进去，因为这个是购物车有的，直接更新当前数组即可）
                    try {
                        wx.setStorageSync('cart', cart_arr)
                        
                        //将数据存入后台
                        wx.request({
                          url: update_url,
                          method: 'POST',
                          data: { campaignId: cartGoodsId, num: num+1, userId: uid},    //参数为键值对字符串
                          success: function (res) {
                            console.log("向后端修改购物车数据：" + res.data.responseBody)
                          }
                        })
                      
                    } catch (e) {
                        console.log(e)
                    }
                    // 返回（在if内使用return，跳出循环节约运算，节约性能）
                    return;
                }
            }
            // 遍历完购物车后，没有对应的item项，把当前项放入购物车数组
            cart_arr.push(this.data.goods_detail);
            //将数据存入后台
            wx.request({
              url: add_url,
              method: 'POST',
              data: { campaignId: good_id, num: 1, userId: uid },    //参数为键值对字符串
              success: function (res) {
                console.log("向后端添加购物车数据：" + res.data.responseBody)
              }
            })
        }
        if (this.data.has_cart == false){
            // 购物车没有数据，把item项push放入当前数据（第一次存放时）
            cart_arr.push(this.data.goods_detail);
            //将数据存入后台
            wx.request({
              url: add_url,
              method: 'POST',
              data: { campaignId: good_id, num: 1, userId: uid },    //参数为键值对字符串
              success: function (res) {
                console.log("向后端添加购物车数据："+res.data.responseBody)
              }
            })
        }
        // 最后，把购物车数据，存放入缓存
        try {
            wx.setStorageSync('cart', cart_arr)
            this.setData({
                has_cart: true
            });
            // 显示提示信息
            wx.showToast({
                title: '添加成功'
            });
            // 返回（在if内使用return，跳出循环节约运算，节约性能）
            return;
        } catch (e) {
            console.log(e);
        }

    },
    toCartPage: function (e) {
        PageContent.loadNavTabBar("../cart");
    },
    buynow:function(e){
      var _this = this;
      var goods_id_arr = [];
      goods_id_arr.push({ id: _this.data.goods_id});
      user.checkLogin().then(res => {
        user.getUserinfoByButton(e).then(res => {
          PageContent.loadNavigate("../../place_order/place_order?goods_id=" + JSON.stringify(goods_id_arr) + "&type=1" + "&provinceList=" + JSON.stringify(_this.data.provinceList) + "&cityList=" + JSON.stringify(_this.data.cityList) )
        })
      }).catch(() => {
        //未登录跳转至登录页面
        wx.showModal({
          title: '提示',
          content: '请登录后进行报名',
          success: function (res) {
            if (res.confirm) {
              console.log('用户点击确定');
              user.getUserinfoByButton(e)
              wx.navigateTo({
                url: '/pages/auth/registerAndLogin/registerAndLogin',
              })
            } else {
              console.log('用户点击取消');
            }
          }
        })
      });
    }
    
  
});